package rk.pisces.jpademo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@SpringBootApplication
@EnableScheduling
public class Application implements ApplicationRunner {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


    private Logger logger = LoggerFactory.getLogger(Application.class);

    @GetMapping("/**")
    public String hello() throws InterruptedException {
        //Thread.sleep(500L);
        return "hello";
    }


    //---------------------
    @GetMapping("/user")
    public Map getUser() {
        logger.info("查询用户信息");
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id", 1);
        userMap.put("name", "xiaoA");
        userMap.put("age", 23);
        userMap.put("time", System.currentTimeMillis());
        return userMap;
    }


    //-------------------
    @GetMapping("/activityUserCount")
    public Long getActivityUserCount() throws InterruptedException {
        logger.info("查询参与人数");
        Thread.sleep(5000l);
        return ActivityUserCount.getCount();
    }


    //------------------
    private Activity activity;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 模拟启动时从数据库加载
        activity = new Activity();
        activity.setChance(0.01D);
    }

    @GetMapping("/chance")
    public Double getChange(String type) {
        //用户倍数 type为2时翻倍
        logger.info("查询概率");
        int userTimes = 1;
        if (type.equals("2")) {
            logger.info("概率翻倍了");
            userTimes *= 2;
        }
        return userTimes * activity.getChance();
    }

    //-----------------

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/times")
    public Long getTimes() {
        logger.info("查询次数");
        Long times = redisTemplate.opsForValue().increment("times");
        return times;
    }

}
